package com.jianzhile.jobs.activities.add;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.jianzhile.jobs.R;
import com.jianzhile.jobs.base.BaseActivity;
import com.jianzhile.jobs.utils.CommonUtil;
import com.jianzhile.jobs.utils.Const;
import com.jianzhile.jobs.utils.FileUtil;
import com.jianzhile.jobs.utils.HttpUtil;
import com.jianzhile.jobs.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class OthersActivity extends BaseActivity implements View.OnClickListener {


    TimePickerView pvTime;
    OptionsPickerView pvOptions;
    @Bind(R.id.vMasker)
    View vMasker;

    private ArrayList<String> optionsItems = new ArrayList<>();

    @Bind(R.id.content_others_font_size_biger)
    ImageButton fontSizeBigerIb;

    @Bind(R.id.content_others_font_size_smaller)
    ImageButton fontSizeSmallerIb;
    @Bind(R.id.content_others_text_color)
    ImageButton fontColorIb;
    @Bind(R.id.content_others_font_bold)
    ImageButton fontBoldIb;
    @Bind(R.id.content_others_insert_photo)
    ImageButton insertPhotoIb;
    @Bind(R.id.content_others_iv)
    ImageView coverIv;
    @Bind(R.id.content_others_add_iv)
    ImageView addIv;
    @Bind(R.id.activity_add_part_job_save_btn)
    public Button publishBtn;
    @Bind(R.id.activity_add_part_job_name_et)
    public EditText nameEt;
    @Bind(R.id.content_others_time_tv)
    public TextView timeTv;
    @Bind(R.id.content_others_pay_way_tv)
    public TextView payTypeTv;
    @Bind(R.id.activity_add_part_job_money_et)
    public EditText moneyEt;
    @Bind(R.id.activity_add_part_job_num_et)
    public EditText numEt;
    @Bind(R.id.activity_add_part_job_address_et)
    public EditText addressEt;
    @Bind(R.id.activity_add_part_job_request_et)
    public EditText requestEt;
    @Bind(R.id.activity_add_part_job_company_et)
    public EditText companyEt;
    @Bind(R.id.activity_add_part_job_contant_et)
    public EditText contantEt;
    @Bind(R.id.activity_add_part_job_phone_et)
    public EditText phoneEt;
    @Bind(R.id.content_others_editor)
    public EditText descriptionEt;

    public int fontSize = 18;

    // 拍照时，图片地址
    private String mFileName = "";
    private Uri mImageUri;
    // 要发送的图片地址列表
    private ArrayList<String> mPathList;
    private String md5;



    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_others);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ButterKnife.bind(this);

        final ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDefaultDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OthersActivity.this.finish();
            }
        });
        ab.setTitle("");

        pvTime = new TimePickerView(this, TimePickerView.Type.ALL);


        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        pvTime.setTitle("开始时间");

        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                timeTv.setText(CommonUtil.formatDate(date.getTime() + ""));
            }
        });


        pvOptions = new OptionsPickerView(this);

        optionsItems.add("当日结");
        optionsItems.add("完工后结");

        pvOptions.setTitle("结算方式");
        pvOptions.setPicker(optionsItems);
        pvOptions.setCyclic(false);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                payTypeTv.setText(optionsItems.get(options1));
            }
        });

    }

    @Override
    public void setListener() {
        timeTv.setOnClickListener(this);
        payTypeTv.setOnClickListener(this);
        fontBoldIb.setOnClickListener(this);
        fontColorIb.setOnClickListener(this);
        fontSizeBigerIb.setOnClickListener(this);
        fontSizeSmallerIb.setOnClickListener(this);
        insertPhotoIb.setOnClickListener(this);
        publishBtn.setOnClickListener(this);
        coverIv.setOnClickListener(this);
        addIv.setOnClickListener(this);
    }

    @Override
    public void initData() {
        phoneEt.setText(mApplication.mUser.mobile+"");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.content_others_time_tv:
                hideInput(v);
                pvTime.show();
                break;
            case R.id.content_others_pay_way_tv:
                hideInput(v);
                pvOptions.show();
                break;
            case R.id.content_others_text_color:

                break;
            case R.id.content_others_insert_photo:

                break;

            case R.id.content_others_iv:
                showDialog();
                break;
            case R.id.content_others_add_iv:
                showDialog();
                break;
            case R.id.activity_add_part_job_save_btn:
                postJob();
                break;
        }
    }

    private void hideInput(View view){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void postJob(){

        if (!phoneEt.getText().toString().trim().matches("^1[345678]\\d{9}$")) {
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (nameEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (timeTv.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (payTypeTv.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (moneyEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (numEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (addressEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (requestEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (companyEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }

        if (contantEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }

        if (descriptionEt.getText().toString().equals("")){
            showTipsDialog(R.string.phone_num_error);
            return;
        }

        // 封装请求数据信息
        Map<String, String> params = new HashMap<>();
        params.put("createUser", mApplication.mUser.uid);
        params.put("mobile", phoneEt.getText().toString());
        params.put("jobname",nameEt.getText().toString());
        params.put("amount", moneyEt.getText().toString());
        params.put("comname", companyEt.getText().toString());
        params.put("contact", contantEt.getText().toString());
        params.put("num", numEt.getText().toString());
        params.put("tel", phoneEt.getText().toString());
        params.put("qq", "123");
        params.put("address", addressEt.getText().toString());
        params.put("detailed", descriptionEt.getText().toString());
        params.put("cover", "aaa");
        params.put("addtime", timeTv.getText().toString());
        params.put("deadline", "aaa");
        params.put("simpleType", "9");

        if (payTypeTv.getText().toString().equals("当日结")){
            params.put("paytype", "1");
        }else{
            params.put("paytype", "2");
        }
        HttpUtil.getInstance().requestWithSecurity(this, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.optInt("code");
                    if (Const.status_1 == code) {

                    } else {
                        ToastUtils.showBottomToast(OthersActivity.this, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtils.showBottomToast(OthersActivity.this, R.string.tips);
            }
        }, CommonUtil.getInstance().getParams(params), Const.PostJob, true);
    }

    private void showTipsDialog(int tipsStringId) {
        final Dialog dialog = new Dialog(this, R.style.prompt_progress_dailog_dimenabled);
        dialog.setContentView(R.layout.modify_dialog_layout);
        TextView content = (TextView) dialog.getWindow().getDecorView().findViewById(R.id.tv_content);
        content.setText(getString(tipsStringId));
        TextView sure = (TextView) dialog.getWindow().getDecorView().findViewById(R.id.tv_confirm);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.TOP); // 设置生效
        // lp.x = 266; // 新位置X坐标
        lp.y = CommonUtil.dip2px(context, 180); // 新位置Y坐标
        // lp.width = 300; // 宽度
        // lp.height = 300; // 高度
        // lp.alpha = 0.7f; // 透明度
        dialogWindow.setAttributes(lp);
        dialog.show();
    }




    private void displayImage() {
        if (!CommonUtil.hasSdcard()) {
            return;
        }
        Bitmap bitmap = CommonUtil.getUriBitmap(this, mImageUri, 640, 400);
        if (null == bitmap || bitmap.isRecycled()) {
            return;
        }
        // 旋转图片
        int angle = CommonUtil.readPictureDegree(mImageUri.getPath());
        bitmap = CommonUtil.rotateBitmap(angle, bitmap);

        mFileName = CommonUtil.saveBitToSD(bitmap, mFileName);
        //csivPortrait.setTag(mFileName);
        // 保证在gallery中能看到刚拍下的照片，发广播
        Intent intent = new Intent();
        Uri uri = Uri.fromFile(new File(mFileName));
        // 设置intent的action，这条action表示要将数据添加进系统的媒体资源库
        intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(uri);
        sendBroadcast(intent);
        // 处理刚拍的照片
       // csivPortrait.setImageURI(Uri.parse("file://" + mFileName));
        Glide.with(this).load("file://" + mFileName).into(coverIv);
    }


    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){

        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1.6);

        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", outputX);

        intent.putExtra("outputY", outputY);

        intent.putExtra("scale", true);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        intent.putExtra("return-data", false);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true); // no face detection

        startActivityForResult(intent, requestCode);

    }


    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        final Dialog dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Button btnTakePic = (Button) view.findViewById(R.id.btn_take_pic);// 拍照
        Button btnFromGallery = (Button) view.findViewById(R.id.btn_from_gallery);// 相册
        Button btnCancelChoose = (Button) view.findViewById(R.id.btn_cancel_choose);// 取消
        btnFromGallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 从相册选择
                launchAlbumActivity();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        btnTakePic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 拍照
                launchCamera();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        btnCancelChoose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        });

        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }


    /**
     * 打开相册activity
     */
    private void launchAlbumActivity() {
        if (null == mPathList) {
            mPathList = new ArrayList<String>();
        }
        Intent intent = new Intent(this, AlbumActivity.class);
        // 移除null,到AlbumActivity不能包含null值，null值只为该页面下添加add image的用途
        ArrayList<String> tempPathList = mPathList;
        Iterator<String> iterator = tempPathList.iterator();
        while (iterator.hasNext()) {
            String tempPath = (String) iterator.next();
            if (null == tempPath) {
                iterator.remove();
            }
        }

        intent.putExtra(Const.SELECTED_PATH_EXTRA, tempPathList);
        // 标识是从PublishActivity来的
        // intent.putExtra(Const.FROM_PUBLISH_EXTRA, true);
        // intent.putExtra(Const.TOPIC_ID_EXTRA, mTopicId);
        // this.startActivityForResult(intent,
        // Const.PUBLISH_ALBUM_REQUEST_CODE);
        startActivityForResult(intent, Const.PUBLISH_ALBUM_REQUEST_CODE);
    }


    /**
     * 拍照
     */
    private void launchCamera() {
        // 指定开启系统相机的Action
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        if (CommonUtil.hasSdcard()) {
            File dir = new File(Const.TAKE_PICTURE_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            mFileName = "image_" + System.currentTimeMillis() + ".jpg";
            mImageUri = Uri.fromFile(new File(Const.TAKE_PICTURE_PATH, mFileName));
            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        }

        startActivityForResult(intent, Const.CAMERA_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Const.CAMERA_REQUEST_CODE:
                // 拍照回来
                cropImageUri(mImageUri, 640, 400, Const.CROP_CAMERA_IMAGE_REQUEST_CODE);

                break;
            case Const.PUBLISH_ALBUM_REQUEST_CODE:
                // 相册回来
                handleAlbumBack(resultCode, data);

                break;
            case Const.CROP_CAMERA_IMAGE_REQUEST_CODE:

                takePicture(resultCode, data);
                break;
            case Const.CROP_GARALY_IMAGE_REQUEST_CODE:

                displayImage();

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 处理拍照的返回结果
     */
    @SuppressWarnings("rawtypes")
    private void takePicture(int resultCode, Intent data) {
        if (Activity.RESULT_OK == resultCode) {

            displayImage();

        }
    }

    private void handleAlbumBack(int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED) {
            if (data != null) {
                ArrayList<String> paths = (ArrayList<String>) data.getSerializableExtra(Const.SELECTED_PATH_EXTRA);
                if (paths != null && !paths.isEmpty()) {
                    if (CommonUtil.hasSdcard()) {
                        File dir = new File(Const.TAKE_PICTURE_PATH);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        mFileName = paths.get(0).substring(paths.get(0).lastIndexOf("/")+1,paths.get(0).length());
                        mImageUri = Uri.fromFile(new File(Const.TAKE_PICTURE_PATH, mFileName));

                        //将获取的文件拷贝到temp文件夹下
                        FileUtil.CopySdcardFile(paths.get(0), Const.TAKE_PICTURE_PATH + mFileName);
                        cropImageUri(mImageUri, 640, 400, Const.CROP_CAMERA_IMAGE_REQUEST_CODE);
                    }

                }
            }

        }
    }

}
